<template>
  <div>
    <el-form ref="form" label-width="80px" class="form">
      <el-form-item label="标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="内容" class="">
        <VueEditor v-model="form.content" class="content" />
      </el-form-item>
      <el-form-item label="栏目" class="categoryList">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            :label="item.id"
            v-for="(item, index) in categoryList"
            :key="index"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="封面">
        <!-- action:上传的接口 -->
        <!-- headers：设置请求头 -->
        <!-- on-success:图片上传成功的钩子函数 -->
        <el-upload
          :action="'/upload' | fixImgUrl"
          :headers="{ Authorization: token }"
          :on-success="uploadSuccess"
          list-type="picture-card"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="form.type">
          <el-radio :label="1">普通文章</el-radio>
          <el-radio :label="2">视频文章</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  data() {
    return {
      categoryList: [],
      checkList: [],
      token: localStorage.getItem("token"),
      form: {
        title: "",
        content: "",
        categories: [],
        cover: [],
        type: 1,
      },
    };
  },
  methods: {
    onSubmit() {
      this.$axios({
        method: "post",
        url: "/post",
        data: this.form,
      }).then((res) => {
        if (res.data.message == "文章发布成功") {
          this.$router.push("/articleList");
        }
      });
    },
    uploadSuccess(res, file, fileList) {
      // 对uid 进行处理 使其变为唯一值
      res.data.uid = res.data.id;
      this.form.cover.push(res.data);
    },
  },
  watch: {
    checkList(newArr) {
      // 将选中列表数组转为API合适的数据格式
      this.form.categories = this.checkList.map((num) => {
        return {
          id: num,
        };
      });
    },
  },
  created() {
    this.$axios({
      url: "/category",
    }).then((res) => {
      if (res.data.data.length > 20) {
        res.data.data.length = 20;
      }
      // 栏目  关注 和 头条 不能显示在页面
      res.data.data.splice(0, 2);
      this.categoryList = res.data.data;
    });
  },
  components: {
    VueEditor,
  },
};
</script>
<style lang="less" scoped>
.form {
  // width: 80px;
  /deep/ input {
    width: 300px;
  }
  .content {
    width: 1000px;
  }
  .categoryList {
    width: 800px;
  }
}
</style>
